package cn.schoolwow.util.module.crypto.cipher.rsa.flow;

import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.check.instance.CheckInstance;
import cn.schoolwow.util.module.crypto.cipher.rsa.domain.RSACipherOption;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class RSADecryptFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        RSACipherOption rsaCipherOption = flowContext.checkInstanceData(RSACipherOption.class);

        CheckInstance.newCheck()
                .notNullCheck(rsaCipherOption.privateKey, "RSA算法私钥不能为空");

        if(null==rsaCipherOption.data||rsaCipherOption.data.isEmpty()){
            flowContext.broken("密文内容为空");
        }

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, rsaCipherOption.privateKey);
        byte[] decoded = Base64.getDecoder().decode(rsaCipherOption.data);
        byte[] decrypted = cipher.doFinal(decoded);
        String plainText = new String(decrypted, StandardCharsets.UTF_8);
        flowContext.putReturnData("string", plainText);
    }

    @Override
    public String name() {
        return "RSA算法解密";
    }

}
